package com.chaoyong.higo.utils;



import com.chaoyong.higo.base.BaseApp;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class RotateUtil {
	
	private static RotateUtil rotate;
	private static AnimationSet animationSet;
	private ImageView ivPic;
	private int drawable;

	public static RotateUtil getInitRotate() {
		if (rotate == null) {
			rotate = new RotateUtil();
			animationSet = new AnimationSet(true);
			// 参数1：从哪个旋转角度开始

			// 参数2：转到什么角度

			// 后4个参数用于设置围绕着旋转的圆的圆心在哪里

			// 参数3：确定x轴坐标的类型，有ABSOLUT绝对坐标、RELATIVE_TO_SELF相对于自身坐标、RELATIVE_TO_PARENT相对于父控件的坐标

			// 参数4：x轴的值，0.5f表明是以自身这个控件的一半长度为x轴

			// 参数5：确定y轴坐标的类型

			// 参数6：y轴的值，0.5f表明是以自身这个控件的一半长度为x轴
			RotateAnimation rotateAnimation = new RotateAnimation(180, 360,

			Animation.RELATIVE_TO_SELF, 0.5f,

			Animation.RELATIVE_TO_SELF, 0.5f);

			rotateAnimation.setDuration(300);

			animationSet.addAnimation(rotateAnimation);
		}
		return rotate;
	}
	
	/**
	 * 取消上一个旋转
	 */
	public void cancelRotate(){
		if(ivPic!=null){
			ivPic.startAnimation(animationSet);
			Bitmap bmp = rotateBitmap(0, setRotatDrawableResource(drawable));
			ivPic.setImageBitmap(bmp);
			ivPic=null;
		}
	}

	/**
	 * 就运行他
	 * @param iv
	 * @param id 图片
	 */
	public void setRotate(ImageView iv, int id) {
		if(iv==null){
			if(ivPic!=null){
				ivPic.startAnimation(animationSet);
				Bitmap bmp = rotateBitmap(0, setRotatDrawableResource(drawable));
				ivPic.setImageBitmap(bmp);
				ivPic=null;
			}
			return;
		}
		iv.startAnimation(animationSet);
		
		if (StringUtils.isEquals(iv, ivPic)) {
			Bitmap bm = rotateBitmap(0, setRotatDrawableResource(id));
			iv.setImageBitmap(bm);
			ivPic=null;
		} else {
			if(ivPic!=null){
				ivPic.startAnimation(animationSet);
				Bitmap bmp = rotateBitmap(0, setRotatDrawableResource(id));
				ivPic.setImageBitmap(bmp);
			}
			ivPic=iv;
			Bitmap bm = rotateBitmap(180, setRotatDrawableResource(id));
			iv.setImageBitmap(bm);
		}
		drawable=id;
	}


	/**
	 * 更改为bitmap对象
	 * 
	 * @param id
	 */
	private Bitmap setRotatDrawableResource(int id) {
		BitmapDrawable drawable = (BitmapDrawable) BaseApp.getContext()
				.getResources().getDrawable(id);

		return drawable.getBitmap();
	}

	/**
	 * 将图片纠正到正确方向
	 * 
	 * @param degree
	 *            ： 图片被系统旋转的角度
	 * @param bitmap
	 *            ： 需纠正方向的图片
	 * @return 纠向后的图片
	 */
	private Bitmap rotateBitmap(int degree, Bitmap bitmap) {
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);

		Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);
		return bm;
	}

}
